#!/usr/bin/perl 
#===============================================================================
#
#         FILE: batch_lib_construct.pl
#
#        USAGE: ./batch_lib_construct.pl 0/1 
#
#  DESCRIPTION: Construct GAG libraries using given precursor and charge information. 
#
#      OPTIONS: 1 for generating libraries, 0 for matching peaks and the default value is 0.
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: ---
#       AUTHOR: Han Hu (hh), hh1985@bu.edu
#      COMPANY: Bioinformatics Program & Center for Biomedical Mass Spectrometry, Boston University
#      VERSION: 1.0
#      CREATED: 8/28/2011 12:47:02 PM
#     REVISION: ---
#===============================================================================

use strict;
use warnings;
my $status = shift @ARGV;
$status = 0 if !defined($status);

if($status == 1) {
	my $script = "tandem_ms_frag_lib_08_19.pl";
	print "The script $script does not exist.\n" unless -e $script;
	open(LIST, "precursor_table.txt") or die "Cannot open the file:$!\n";
	while(my $line = <LIST>) {
		chomp $line;
		my ($pre_mz, $pre_z) = split /\t/, $line;
		system("perl $script -x $pre_mz -z $pre_z");
		print "Cheers! Precursor $pre_mz and charge $pre_z is done!\n";
	}
	close(LIST);
} else {
	#-------------------------------------------------------------------------------
	#  Match the data files against the library.
	#-------------------------------------------------------------------------------
	my $dir = "./data";
	opendir(DIR, $dir) or die "Cannot open $dir:$!\n";
	my $MatchScript = "MatchPeak.pl";
	print "$MatchScript does not exist!\n" unless -e $MatchScript;
	while (my $file = readdir(DIR)) {
		next unless $file =~ m/\.dta$/;
		my @info = ($file =~ m/^(.*)_(.*)\.dta$/);
		## Check the lib file.
		my $libfile = "gag_library_$info[1].csv";
		die "The corresponding lab data for $info[1] does not exist.\n" unless -e "./output/$libfile";  
		## Match $file aganist the library!
		system("perl $MatchScript -x $info[1]");
		print "The match process for $info[1] is finished.\n"; 
	}
	closedir(DIR);
}


